import { createRouter, createWebHistory } from 'vue-router'
import { initConstantRoutes, addDynamicRoutes } from './utils'
import { getInfo } from '@/api/system/user'
import { useUserStore } from '@/stores/user'
import { useTokenStore } from '@/stores/token'
import { getToken } from '@/utils/auth'
import nprogress from 'nprogress'
const router = createRouter({
  history: createWebHistory(),
  routes: initConstantRoutes()
})

// 全局前置守卫
router.beforeEach(async (to, from, next) => {
  nprogress.start()
  const tokenStore = useTokenStore()
  if (getToken().accessToken) {
    const userStore = useUserStore()
    // 判断是否初始化user
    if (!userStore.id) {
      try {
        const userInfo = await getInfo()
        userStore.SET_USER(userInfo.data)
      } catch (error) {
        tokenStore.clearToken()
        return next('/login')
      }
    }
    // 判断当前是否添加了动态路由
    if (!router.hasRoute('Welcome')) {
      addDynamicRoutes()
      return next({ ...to, replace: true })
    }
    if (to.path === '/login') {
      return next('/')
    }
    next()
  } else {
    if (to.path == '/login' || to.path == '/error/401') {
      next()
    } else {
      next({ path: '/login' })
    }
  }
})

// 全局后置守卫
router.afterEach((to, from) => {
  nprogress.done()
})
export default router
